package com.hmall.item.web;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;


    @GetMapping("list")
    public PageDTO<Item> list(@RequestParam("page") int page,@RequestParam("size") int size) {
        return itemService.listByPage(page, size);
    }

    @PostMapping
    public void add(@RequestBody Item item) {
        itemService.add(item);
    }

    @GetMapping("/{id}")
    public Item getById(@PathVariable("id") Long id) {
        return itemService.getById(id);
    }

    @PutMapping
    public void updateById(@RequestBody Item item) {
        itemService.updateItem(item);
    }

    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable("id") Long id) {
        itemService.deleteItem(id);
    }

    @PutMapping("/status/{id}/{status}")
    public void updateStatus(@PathVariable("id") Long id, @PathVariable("status") Integer status) {
        // 构建更新条件
        LambdaUpdateWrapper<Item> query = new LambdaUpdateWrapper<>();
        // update item set status = ? where id = ?
        query.eq(Item::getId, id);
        query.set(Item::getStatus, status);
        query.set(Item::getUpdateTime, new Date());
        itemService.update(query);
    }

    /**
     * 更新库存接口
     * @param id
     * @param num
     */
    @PutMapping("stock/{itemId}/{num}")
    public void reduceStock(@PathVariable("itemId") Long id,@PathVariable("num") Integer num){
        itemService.reduceStock(id,num);
    }
}
